import store from "../store"; // 确保路径正确

class soundManger {
	/**
	 * 构造函数
	 * @param {Object} options - 配置选项
	 * @param {string} [options.sendAudioUrl] - 发送消息的音频文件路径
	 * @param {string} [options.receiveAudioUrl] - 接收消息的音频文件路径
	 * @param {Array<number>} [options.vibratePattern] - 振动模式
	 */
	constructor(options = {}) {
		const msgState = store.state.msg;
		this.userId = msgState.user?.userId;
		const initialSoundStates = msgState.stateConfig?.sound || {};

		// 合并默认配置和传入配置
		this.config = {
			sendAudioUrl: options.sendAudioUrl || "/static/voic/9411.wav",
			receiveAudioUrl: options.receiveAudioUrl || "/static/voic/4082.wav",
			vibratePattern: options.vibratePattern || [100, 50, 100], // 振动模式：震100ms，停50ms，震100ms
		};

		// 状态存储: key为聊天会话ID, value为状态(0, 1, 2)
		this.states = new Map();
		// 初始化状态：如果从store获取的是对象，则转换为Map
		if (initialSoundStates && typeof initialSoundStates === "object") {
			Object.entries(initialSoundStates).forEach(([id, state]) => {
				this.states.set(id, state);
			});
		}

		// 音频实例管理
		this.audioInstances = {
			send: this._createAudioInstance(this.config.sendAudioUrl),
			receive: this._createAudioInstance(this.config.receiveAudioUrl),
		};

		// 检查振动支持 (uni-app 环境)
		this.isVibrateSupported = uni.getSystemInfoSync().vibrateSupported || false;
	}

	/**
	 * 内部方法：创建并配置一个InnerAudioContext实例
	 * @param {string} url - 音频文件路径
	 * @returns {uni.createInnerAudioContext} - 创建的音频实例
	 */
	_createAudioInstance(url) {
		const audio = uni.createInnerAudioContext();
		audio.src = url;
		// 监听错误
		audio.onError((err) => {
			console.error(`音频加载失败 (${url}):`, err.errMsg);
		});
		return audio;
	}

	/**
	 * 根据ID设置状态
	 * @param {string|number} id - 唯一标识符 (通常是聊天会话ID)
	 * @param {number} state - 0:静音, 1:振动, 2:声音
	 * @returns {boolean} 设置是否成功
	 */
	setState(id, state) {
		if (typeof id === "undefined" || id === null) {
			console.error("ID不能为空");
			return false;3
		}
		if (![0, 1, 2].includes(state)) {
			console.error("无效的状态值，必须是 0, 1, 或 2");
			return false;
		}
		console.log(id, state);
		this.states.set(id, state);
		// 同步状态到Vuex，将Map转换为普通对象
		store.commit("msg/SET_stateConfig", {
			...store.state.msg.stateConfig,
			sound: Object.fromEntries(this.states),
		});
		return true;
	}

	/**
	 * 根据ID获取状态
	 * @param {string|number} id - 唯一标识符
	 * @returns {number} 当前状态, 默认为1 (振动)
	 */
	getState(id) {
		const state = this.states.get(id);
		return state !== undefined ? state : 2;
	}

	/**
	 * 根据ID和消息类型执行相应的提醒动作
	 * @param {string|number} id - 唯一标识符 (聊天会话ID)
	 * @param {'send'|'receive'} type - 消息类型：'send' 或 'receive'
	 */
	playAction(id, type) {
		try {
			if (!["send", "receive"].includes(type)) {
				console.error("无效的类型，必须是 'send' 或 'receive'");
				return;
			}

			const state = this.getState(id);
			console.log('播放类型', state);

			switch (state) {
				case 0:
					// 静音，不执行任何操作
					break;
				case 1:
					this._playVibration();
					break;
				case 2:
					this._playSound(type);
					break;
			}
		} catch (e) {
			console.error(e);
		}


	}

	/**
	 * 内部方法：播放振动
	 */
	_playVibration() {

		uni.vibrateShort()
	}

	/**
	 * 内部方法：播放声音
	 * @param {'send'|'receive'} type - 消息类型
	 */
	_playSound(type) {
		const audio = this.audioInstances[type];
		if (audio) {
			audio.play()
		}
	}
}

export default soundManger;